import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wan_android/res/colors.dart';
import 'package:flutter_wan_android/res/dimens.dart';
import 'package:flutter_wan_android/utils/share_utils.dart';
import 'package:flutter_wan_android/utils/url_launcher_utils.dart';
import 'package:flutter_wan_android/widgets/home_widgets.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {
  final String url;
  final String title;

  const WebViewPage(this.url, this.title, {Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _WebViewState(url, title);
  }
}

class _WebViewState extends State<WebViewPage> {
  final String url;
  final String title;

  bool _offstage; //默认显示

  _WebViewState(this.url, this.title);

  //定义一个key
  GlobalKey _key = GlobalKey();

  _getRenderBox(_) {
    //获取`RenderBox`对象
    RenderBox renderBox = _key.currentContext.findRenderObject();
  }

  @override
  void initState() {
    //监听Widget是否绘制完毕
    WidgetsBinding.instance.addPostFrameCallback(_getRenderBox);

    super.initState();
    _offstage = false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: PreferredSize(
            child: AppBar(
              title: Text(
                title,
                style: TextStyle(fontSize: XDimens.appBarTitleTextSize),
              ),
              actions: <Widget>[
                IconButton(
                    //设置key
                    key: _key,
                    icon: Icon(
                      Icons.more_vert,
                      color: XColors.white,
                    ),
                    onPressed: () {
                      getPosition();
                      _showMenu(context);
                    })
              ],
            ),
            preferredSize: Size.fromHeight(XDimens.appBarHeight)),
        body: Builder(builder: (context) {
          return Stack(
            alignment: Alignment.center,
            children: <Widget>[
              buildWebView(),
              Offstage(
                offstage: _offstage,
                child: ProgressView(),
              )
            ],
          );
        }));
  }

  void _showMenu(BuildContext context) {
    PopupMenuButton<String> pop = _popMenu();
    showMenu(
      context: context,
      position:
          RelativeRect.fromLTRB(getPosition().dx, getPosition().dy + 8, 8, 0),
      items: pop.itemBuilder(context),
    ).then((newValue) {
      /*if (!mounted) return null;
      if (newValue == null) {
        if (pop.onCanceled != null) pop.onCanceled();
        return null;
      }*/
      if (pop.onSelected != null) pop.onSelected(newValue);
    });
  }

  PopupMenuButton _popMenu() {
    return PopupMenuButton<String>(
      itemBuilder: (context) => <PopupMenuItem<String>>[
        PopupMenuItem(
            value: 'language',
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Icon(Icons.language),
                Padding(padding: EdgeInsets.only(left: 10)),
                Text('浏览器打开'),
              ],
            )),
        PopupMenuItem(
            value: 'share',
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Icon(Icons.share),
                Padding(padding: EdgeInsets.only(left: 10)),
                Text('分享'),
              ],
            )),
      ],
      onSelected: (String value) {
        print("position value ::" + value);
        switch (value) {
          case 'language':
            UrlLauncherUtils.launchURL(url);
            break;
          case 'share':
            ShareUtils.share(title, url);
            break;
        }
      },
    );
  }

  Offset getPosition() {
    //获取控件的大小
    Size size = _key.currentContext.size;
    print("position width ::${size.width}  height:: ${size.height}");

    //获取控件左上顶点的坐标
    RenderBox renderBox = _key.currentContext.findRenderObject();
    var offset = renderBox.localToGlobal(Offset.zero);
    print("position left top dx::${offset.dx} dy:: ${offset.dy}");

    //获取控件左下顶点的坐标（正下方）
    var offset2 = renderBox.localToGlobal(Offset(0.0, size.height));
    print("position left bottom dx::${offset2.dx} dy:: ${offset2.dy}");

    return offset2;
  }

  Widget buildWebView() {
//    Future.delayed(Duration(seconds: 2) );

    return WebView(
      initialUrl: url,

      ///WebView 创建完成之后的回调
      onWebViewCreated: (controller) {},

      ///加载前拦截url，做一些处理
//        navigationDelegate: (request){
//          return  NavigationDecision.navigate;
//        },
      ///加载完成调用
      onPageFinished: (url) {
        setState(() {
          print("onPageFinished");
          _offstage = true;
        });
      },
      javascriptMode: JavascriptMode.unrestricted,
    );
  }
}
